/*
 * @Author: 缄默
 * @Date: 2021-12-12 15:17:59
 * @LastEditors: 缄默
 * @LastEditTime: 2021-12-14 10:06:30
 */

//原型模式

#include <iostream>

using namespace std;

class Prototype {
public:
    virtual Prototype* clone() = 0;
    virtual ~Prototype() { }
};

class ConcretePrototype : public Prototype {
private:
    static int count;

public:
    ConcretePrototype() {
        count++;
     }

    //通过二进制内存拷贝，绕过构造函数
    Prototype* clone() {
        cout << "clone copy..." << endl;

        //从左至右以此是
        //强制类型转换 申请内存 计算所需申请内存大小
        Prototype* p = reinterpret_cast<Prototype*>(malloc(sizeof(*this)));

        //内存拷贝函数 将从this开始的sizeof(*this)大小的内存拷贝到p开始的地址
        memcpy(p, this, sizeof(*this));
        return p;
    }
    static void show() {
        cout << count << endl;
    }
};

int ConcretePrototype::count = 0;

int main() {
    Prototype* prototype = new ConcretePrototype();
    cout << prototype << endl;
    Prototype* prototype1 = prototype->clone();
    cout << prototype1 << endl;
    Prototype* prototype2 = prototype->clone();
    cout << prototype2 << endl;

    //输出构造函数被调用的次数 从输出可以看到构造函数仅被调用一次
    ConcretePrototype::show();
    delete prototype;
    free(prototype1);
    free(prototype2);

    return 0;
}